package sit.mycatalog.ejb.sess;

import java.io.File;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import sit.mycatalog.ejb.dao.ItemDao;
import sit.mycatalog.jpa.Item;
import sit.mycatalog.util.AbstractSess;
import sit.mycatalog.util.ConfigConstant;

/**
 * Session Bean implementation class ItemSess
 */
@Stateless
@LocalBean
public class ItemSess extends AbstractSess {
	@EJB
	ItemDao m_daoItem;
	
    public ItemSess() {
    }
    
    public Item getItem(String p_strItem) throws Exception {
    	return m_daoItem.findByPrimaryKey(p_strItem);
    }
    
    public List<Item> getByCatid(Integer p_intCatid) throws Exception {
    	return m_daoItem.findByCatid(p_intCatid);
    }
    
    public List<Item> getHotItem() throws Exception {
    	return m_daoItem.findHotItem();
    }
    
    public List<Item> getItemByKeyword(String p_strKeyword) throws Exception {
    	return m_daoItem.findItemByKeyword(p_strKeyword);
    }
    
    public List<Item> getAll() throws Exception {
    	return m_daoItem.findAll();
    }
    
    public boolean createItem(Item p_item) throws Exception {
    	return m_daoItem.create(p_item);
    }
    
    public boolean updateItem(Item p_item) throws Exception {
    	boolean complete = false;
    	
    	try {
			Item item = m_daoItem.findByPrimaryKey(p_item.getItem());
			item.setCatid(p_item.getCatid());
			item.setDescription(p_item.getDescription());
			item.setHot(p_item.getHot());
			item.setPrice(p_item.getPrice());
			
			complete = true;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
    	
    	return complete;
    }
    
    public boolean deletItem(String p_strItem) throws Exception {
    	boolean complete = false;
    	
    	try {
    		Item item = m_daoItem.findByPrimaryKey(p_strItem);
    		if(item.isCheck()) {
	    		String strImg = item.getImgpath();
	    		
				if(m_daoItem.remove(p_strItem)) {
					if((strImg != null) && (!strImg.equals(""))) {
						File fileImage = new File(ConfigConstant.ITEM_IMAGE_PATH + strImg);
						if(fileImage.exists()) {
							fileImage.delete();
						}
					}
					
					complete = true;
				}
    		} else {
    			complete = true;
    		}
		} catch (Exception e) {
			sessionContext.setRollbackOnly();
			e.printStackTrace(System.out);
		}
    	
    	return complete;
    }
    
    public void updateImagePath(String p_strItem, String p_strPath) throws Exception {
    	Item item = m_daoItem.findByPrimaryKey(p_strItem);
    	item.setImgpath(p_strPath);
    }
}

